package com.world.spire.office.free;


import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.Range;
import com.aspose.words.SaveFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 创建人: wangpengfei
 * 创建日期: 2019-07-22
 * 功能描述:
 */
public class OfficeToPdfUtils {

    /**
     * The constant LOG.
     *
     */
    private static final Logger LOG = LoggerFactory.getLogger(OfficeToPdfUtils.class);

    // 凭证
    private static final String  license =
            "<License>\n"+
                    "  <Data>\n"+
                    "    <Products>\n"+
                    "      <Product>Aspose.Total for Java</Product>\n"+
                    "      <Product>Aspose.Words for Java</Product>\n"+
                    "    </Products>\n"+
                    "    <EditionType>Enterprise</EditionType>\n"+
                    "    <SubscriptionExpiry>20991231</SubscriptionExpiry>\n"+
                    "    <LicenseExpiry>20991231</LicenseExpiry>\n"+
                    "    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n"+
                    "  </Data>\n"+
                    "  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n"+
                    "</License>";

    /**
     * 获取license
     *
     * @return
     */
    public static boolean getWordLicense() {
        boolean result = false;
        try {
            //InputStream license = new FileInputStream(new File(IoTools.getABSPATH() + "WEB-INF/license.xml"));// license路径
            InputStream is = new ByteArrayInputStream(license.getBytes(StandardCharsets.UTF_8));
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }



    public static void word2Pdf(String resourceFilePath, String destFilePath) {
        InputStream wordIn = null;
        try {
             wordIn = new FileInputStream(new File(resourceFilePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        FileOutputStream fileOS = null;
        // 验证License
        if (!getWordLicense()) {
            LOG.error("验证License失败！");
            return;
        }
        try {
            Document doc = new Document(wordIn);
            fileOS = new FileOutputStream(new File(destFilePath));
            // 保存转换的pdf文件
            doc.save(fileOS, SaveFormat.PDF);
        } catch (Exception e) {
            LOG.error("error:", e);
        } finally {
            try {
                if(fileOS != null){
                    fileOS.close();
                }
                if(wordIn != null){
                	wordIn.close();
                }
            } catch (IOException e) {
                LOG.error("error:", e);
            }
        }
    }

    /**
     * aspose word 替换文字/图片。
     * @param url  原文件路径
     * @param saveurl 保存路径
     * @param params {key:value,"$年份$":"2020","$签字1$":"$pic:d/qz1.jpg"} key 为要被替换的字符串，value 为替换为的字符串，替换为图片，则value为$pic:+图片路径
     * @return
     */
    public static boolean asposeReplace(String url,String saveurl,Map<String, String> params){
        if(!getWordLicense()){
            return false;
        }
        File file = new File(url);
        if(!file.exists()){
            return false;
        }
        try {
            Document doc = new Document(url);
            Range range = doc.getRange();
            for(String key:params.keySet()){
                String value = params.get(key);
                if(value.startsWith("$pic:")){
                    value = value.substring(5);
                    //key = key.replace("\\", "\\\\");
                    key = key.replace("$", "\\$");
                    //key = key.replace("[", "\\[");
                    //key = key.replace("]", "\\]");
                    key = key.replace("(", "\\(");
                    key = key.replace(")", "\\)");
                    key = key.replace("|", "\\|");
                    key = key.replace("+", "\\+");
                    key = key.replace("?", "\\?");
                    key = key.replace("*", "\\*");
                    //range.replace(Pattern.compile(key),new ReplaceAndInsertImage(value) , false);
                }else{
                    range.replace(key, value, true, false);
                }
            }
            doc.save(saveurl);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    public static void main(String[] args) throws Exception {
//        Map<String, String> params = new HashMap<String, String>();
//        params.put("$project$", "陕西西安工程");
//
//        params.put("$remark$", "1. 创建问题的时候   circuit_problem_status 应该默认1  是正常 现在是空（好像也不影响判断）\n" +
//                "2.问题列表不应该显示已退回的数据\n" +
//                "3.问题中 不同类型 和不同状态审核 是否分开页面，因为只有个别字段有差异\n" +
//                "4.所有返回列表 都不应该，列表的上一级应该是工作台");
//
//        params.put("$qianzi$", "$pic:C:\\Users\\pc\\Desktop\\5a0b3e3ddd93416283bbc7f8240e0bf4.png");
//
//        params.put("$pic$", "$pic:C:\\Users\\pc\\Desktop\\未标题-1.png");
//
//        asposeReplace("C:\\Users\\pc\\Desktop\\1.doc", "C:\\Users\\pc\\Desktop\\2.doc", params);

        word2Pdf("C:\\settle-pdf\\model\\6b8e6f17b658492c9871de282f20ebf6.doc","C:\\settle-pdf\\1.pdf");
        //doc.save("C:\\Users\\pc\\Desktop\\2.doc");
        System.out.println("完成！！！！！！！！！！！");
    }

}
